package com.aggregate.pay.transfar.test.client;

import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import org.apache.http.Header;
import org.apache.http.NameValuePair;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpUriRequest;
import org.apache.http.client.methods.RequestBuilder;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.message.BasicHeader;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.aggregate.pay.transfar.support.HttpClient;

public class TransfarHttpClient implements HttpClient {
	
	private static Logger log = LoggerFactory.getLogger(TransfarHttpClient.class);
	
	private static final String CHARSET = "UTF-8";
	
	@Override
	public String post(String path, Map<String, String> params) {
		

		List<NameValuePair> valuePairs = new ArrayList<NameValuePair>(params.size());
		for (Map.Entry<String, String> entry : params.entrySet()) {
			NameValuePair nameValuePair = new BasicNameValuePair(entry.getKey(), String.valueOf(entry.getValue()));
			valuePairs.add(nameValuePair);
		}
		UrlEncodedFormEntity formEntity = null;
		try {
			formEntity = new UrlEncodedFormEntity(valuePairs, "utf-8");
			formEntity.setContentType("application/x-www-form-urlencoded;charset=utf-8");
		} catch (UnsupportedEncodingException e1) {
			e1.printStackTrace();
		}
		
		log.debug("请求地址：{}", path);
		//log.debug("请求内容：{}", reqBody);
		Header header = new BasicHeader("Content-Type", 
				"application/x-www-form-urlencoded;charset=utf-8");
		HttpUriRequest httpUriRequest = RequestBuilder
				.post()
				.setHeader(header)
				.setUri(path)
				.setEntity(formEntity)
				.build();
		CloseableHttpClient httpClient = HttpClientFactory.createHttpClient();
		CloseableHttpResponse response;
		try {
			response = httpClient.execute(httpUriRequest);
			int status = response.getStatusLine().getStatusCode();
			log.debug("远程接口返回状态：{}", response.getStatusLine());
	        if (status == 200) {
	        	String resBody = EntityUtils.toString(response.getEntity(), CHARSET);
	        	log.debug("响应内容：{}", resBody);
				return resBody;
	        } 
		} catch (Exception e) {
			log.error("远程接口调用失败", e);
		} 
		return null;
	}

}
